package com.dingding.service.activity.core.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.dao.impl.BaseDaoImpl;
import com.dingding.common.core.beans.PromotionDayStat;
import com.dingding.common.core.beans.Promotionstat;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.service.activity.core.dao.IPromotionDayStatDao;
import com.dingding.service.activity.core.dao.IPromotionstatDao;

/**
 * @Description:推广商统计dao
 * @author fengshuonan
 * @date 2016年4月26日 下午8:35:54
 */
@Component("promotionstatDao")
public class PromotionstatDaoImpl extends BaseDaoImpl<Promotionstat> implements IPromotionstatDao {

	private Logger log = Logger.getLogger(this.getClass());
	
	@Resource(name = "promotionDayStatDao")
	private IPromotionDayStatDao promoionDayStatDao;
	
	/**
	 * @Description: 把当天微信公众号关注数记录到总数中
	 * @author fengshuonan
	 * @return void
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void recordDayAttendStat() {
		
		/**
		 *  查找当天所有推广商的统计情况
		 */
		List<PromotionDayStat> stats = null;
		
		try {
			stats = promoionDayStatDao.queryCriteriaList(Restrictions.eq("recordDate", DateFormatUtil.yyyy_MM_ddDate(new Date())));
		} catch (Exception e) {
			log.error("把当天微信公众号关注数记录到总数中出错！PromotionstatDaoImpl : recordDayAttendStat",e);
			return;
		}
		
		if(stats == null || (stats != null && stats.size() <= 0) ){
			log.error("把当天微信公众号关注数记录到总数中出错！PromotionstatDaoImpl : recordDayAttendStat");
			return;
		}
		
		/**
		 * 查询统计表中的所有数据
		 */
		List<Promotionstat> recordStats = null;
		
		try {
			recordStats = this.queryAll();
		} catch (Exception e) {
			log.error("把当天微信公众号关注数记录到总数中出错！PromotionstatDaoImpl : recordDayAttendStat",e);
			return ;
		}
		
		if(recordStats == null || (recordStats != null && recordStats.size() <= 0) ){
			log.error("把当天微信公众号关注数记录到总数中出错！PromotionstatDaoImpl : recordDayAttendStat");
			return ;
		}
		
		/**
		 * 把所有当天的统计数据都放入总的统计中
		 */
		ArrayList<Integer> shops = new ArrayList<Integer>();
		
		for(Promotionstat stat : recordStats){
			shops.add(stat.getShopId());
		}
		
		for(PromotionDayStat dayStat : stats){
			
			if(!shops.contains(dayStat.getShopId())){
				
				Promotionstat promotionstat = new Promotionstat(ToolUtil.getUid(),dayStat.getShopId(),"推广商" + dayStat.getShopId(),0,0,new Date(),true,0);
				super.save(promotionstat);
				recordStats.add(promotionstat);
			}
			
			for(Promotionstat stat : recordStats){
				
				if(dayStat.getShopId().equals(stat.getShopId())){
					stat.setAttendNum(stat.getAttendNum() + dayStat.getAttendNum());
					break;
				}
			}
		}
	}
}
